/*
 * @Description: 
 * @Autor: lizhengkun
 * @Date: 2021-08-10 11:01:24
 */
import { GetToken } from '@/utils/session';
import { store } from '@/redux';
import { GetStroageItem, SetStroageItem } from './storage-utils';
import { SessionConst } from '@/constants/storage';

export const checkAuth = async (props: any) => {
  // 小程序授权登录联调
  if (
    !GetStroageItem(SessionConst.CMB_APP_DONE_AUTH, false, true) &&
    !process.env.REACT_APP_API
  ) {
    SetStroageItem(SessionConst.CMB_APP_DONE_AUTH, true, true);
    props.history.replace({
      // pathname: '/cmb-login',
      pathname: '/login',
      state: { ...props.location } //记录从哪个页面跳去登录的
    });
    return false;
  }
  // 权限认证 进入路由之前的校验 （例如：是否已经登录 || 是否拥有该路由进入权限）
  const menuFlag = await checkMenu();
  return checkToken(props) && menuFlag;
};

export const checkToken = (props: any) => {
  const token = GetToken();
  if (!token) {
    // props.history.replace('/cmb-login');
    props.history.replace('/login');
    return false;
  }
  return true;
};

export const checkMenu = async () => {
  // 速度加载慢
  store.dispatch({ type: 'common/getOrgTreeDataSaga' }),
  await Promise.all([
    store.dispatch({ type: 'common/getUserMenuSaga' }),
    store.dispatch({ type: 'common/getUserInfoSaga' })
    // store.dispatch({ type: 'common/getOrgTreeDataSaga' }),
  ]);
  return true;
};

// 审批token获取 TODO
/**
 * 设置cookie
 */
export function setCookie(name: string, value: string, exdays = 5) {
  const d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  const expires = d.toUTCString();
  document.cookie = `${name}=${value};expires=${expires};path=/`;
}
/**
 * 获取制定名称的cookie的值
 */
export function getCookie(name: string) {
  const cookieReg = new RegExp(`(^|)${name}=([^;]*)(;|$)`);
  const arr = document.cookie.match(cookieReg);
  if (arr && arr.length > 1) {
    return unescape(arr[2]);
  }
  return null;
}
/**
 * 删除制定cookie
 * @param {string} name
 */
export function delCookie(name: string) {
  const exp = new Date();
  exp.setTime(exp.getTime() - 1);
  const cval = getCookie(name);
  if (cval != null) {
    document.cookie = `${name}=${cval};expires=${exp.toUTCString()};path=/`;
  }
}

export const deleteToken = () => {
  // delCookie(userToken);
};

export const setToken = (data: string) => {
  // setCookie(userToken, data);
};

export const getToken = () => {
  return GetToken();
};
